package edu.towson.forensics.securephone;

/** 
 * 
 * 
 */

import java.io.BufferedReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class SecurePhoneConnectionGateway extends Service {
  	
  ServerSocket serverSocket;
  Socket clientSocket = null;
  PrintWriter out = null;
  BufferedReader in = null;
  
  private int unSecureCode=0,notSecureCode=0;
  
  private final int SAFE_CODE=0;
  
  private final int START_DIRECTLY_BY_INTENT=1;
  
  protected static final String TAG_FOR_LOG_FILE="SecurePhone";
  
  //** Start Service for first time which start timing for receiving Intent from PC
  @Override
  public void onCreate() {    

  	  if (!checkExistingServiceInstance())
	  {
    	unSecureCode=START_DIRECTLY_BY_INTENT;
    	UnSecurePhone();
	  } 
  }
  
  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
      Toast.makeText(this, "Gateway service starting", Toast.LENGTH_SHORT).show();
      
    
	  
      //** parameters which has to send to phone for first step before timeout
      String hostIpOrName=null;
      int hostPortNo=-1;
  
	  //** Get IP and Port by Intent  
	  try
	  {
      hostIpOrName= intent.getStringExtra("hostIpOrName");        //IP Address of host	      
      hostPortNo = Integer.parseInt(intent.getStringExtra("hostPortNo"));   //Host Port Number
      Toast.makeText(this, hostIpOrName + hostPortNo, Toast.LENGTH_SHORT).show();
	  }
	  
	  //** If intent is not original and contain the predicted data
	  catch (Exception e)
	  {					
	  unSecureCode=2;
	  UnSecurePhone();
	  }

	  /** Establish a connection if PortNo is available otherwise that is not secure PC 
	   * !0 and !-1 and !service start from other than broadcast receiver 
	  */	  
      if (hostPortNo>=0 && hostIpOrName.equals("PCsendingData") && unSecureCode==SAFE_CODE)
      {
    	startService(new Intent()
  				.setAction("edu.towson.forensics.securephone.action")
  				.addCategory("edu.towson.forensics.securephone.category")
  				.putExtra("GatewayReceivedTime", System.currentTimeMillis())
  				.putExtra("hostIpOrName", "GatewayService").putExtra("hostPortNo", String.valueOf(hostPortNo)));
    	
    	stopSelf();
      }
      else 
      {
    	  if (unSecureCode==SAFE_CODE)
    		  unSecureCode=3;
    	  UnSecurePhone();
  		}

      return START_STICKY;
  }

  @Override
  public IBinder onBind(Intent intent) {
      // We don't provide binding, so return null
      return null;
  }
  
  @Override
  public void onDestroy() {
    Toast.makeText(this, "Gateway service done", Toast.LENGTH_SHORT).show(); 
  }
  
  private boolean checkExistingServiceInstance()
  {
		/** Check the existing service in the list of running services on ActivityManager.
		 *  if service could find as running service will send intent to stop all instance of 
		 *  service by calling SecurePhoneConnection.stopSecurePhoneService and passing existing 
		*/
	    ActivityManager manager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
	    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) 
	    	{
	        	if ("edu.towson.forensics.securephone.SecurePhoneConnection".equals(service.service.getClassName()))
	        			return true;
	    	}
	    return false;
  }
  
  		/* unSecureCode 
		 * 1: run service directly without first USB detection , 2: incomplete or invalid Extras 
		 * 11:Invalid PC MAC address
		 */	
	  	//** PC is recognized as unsecured PC 
	  	protected void UnSecurePhone(){
			Toast.makeText(this, "Gateway UnSecurePC "+String.valueOf(unSecureCode), Toast.LENGTH_LONG).show();
			if (unSecureCode==START_DIRECTLY_BY_INTENT)
				stopSecurePhoneService(this);
			else
				SecurePhoneConnection.stopSecurePhoneService(this);			
		}
		
		/* notSecureCode
		 * 1: Timeout for receive intent from PC
		 */
		//** PC is recognized as unsecured PC 
		protected void NotSecurePhone(){
			Toast.makeText(this, "Gateway Not SecurePC "+String.valueOf(notSecureCode), Toast.LENGTH_LONG).show();
			this.stopSecurePhoneService(this);
		}	
		
		private void stopSecurePhoneService(Context context)
		{
			//stop gateway service
			context.stopService(new Intent("edu.towson.forensics.securephone.gateway.action")
														.addCategory(Intent.CATEGORY_DEFAULT)
														.addCategory("edu.towson.forensics.securephone.category"));
		}
}

